﻿using FindProject.Interfaces;
using FindProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FindProject.Common
{
    internal static class FolderHelper
    {
        internal static FolderInfo GetFolderInfo(string folderPath)
        {
            var folderInfo = new FolderInfo()
            {
                FolderPath = folderPath,
                FolderName = folderPath.Substring(folderPath.LastIndexOf("\\") + 1),
                CreateTime = Directory.GetCreationTime(folderPath)
            };
            return folderInfo;
        }

        internal static string GetFolderName(string folderPath)
        {
            return folderPath.Substring(folderPath.LastIndexOf("\\") + 1);
        }

        internal static List<string> GetProjectPathList(string repositoryPath)
        {
            var matchProjectPathList = new List<string>();
            string[] folders = Directory.GetDirectories(repositoryPath); // 文件夹名称
            var matchRules = AppContext.ResolveAll<IMatchProjectPath>(); // 项目 .sln 文件匹配规则

            // 遍历根目录是否能找到解决方案
            foreach (var matchRule in matchRules)
            {
                var result = matchRule.MatchProject(repositoryPath, "");
                if (!string.IsNullOrEmpty(result) && !matchProjectPathList.Contains(result))
                {
                    matchProjectPathList.Add(result);
                }
            }

            // 遍历第一层文件夹
            foreach (var fullPath in folders)
            {
                string projectFolderName = new DirectoryInfo(fullPath).Name; // 项目文件夹名称

                foreach (var matchRule in matchRules)
                {
                    var result = matchRule.MatchProject(fullPath, projectFolderName);
                    if (!string.IsNullOrEmpty(result) && !matchProjectPathList.Contains(result))
                    {
                        matchProjectPathList.Add(result);
                    }
                }
            }

            return matchProjectPathList;
        }
    }
}
